package com.skplanet.oneplusonewindow.moimserver.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.skplanet.oneplusonewindow.moimserver.dao.MemberDAO;
import com.skplanet.oneplusonewindow.moimserver.dao.MoimDAO;
import com.skplanet.oneplusonewindow.moimserver.dao.UserDAO;
import com.skplanet.oneplusonewindow.moimserver.domain.Moim_Member;
import com.skplanet.oneplusonewindow.moimserver.domain.Moim_Moim;
import com.skplanet.oneplusonewindow.moimserver.domain.Moim_User;



@Service(value="moimService")
@Transactional
public class MoimService {
	@Autowired
	private MoimDAO moimDAO;
	@Autowired
	private MemberDAO memberDAO;
	@Autowired
	private UserDAO userDAO;	
	
	@Transactional(readOnly = true)
	public List<Moim_Moim> getAllMoim(){
		List<Moim_Moim> moims = moimDAO.getAll();
		return moims;
	}
	@Transactional(readOnly = true)
	public Moim_Moim getMoim(long id){
		Moim_Moim moim = moimDAO.findUniqByObject("id", id);
		return moim;
	}
	@Transactional(readOnly = true)
	public Moim_Moim getMoim(String name){
		Moim_Moim moim = moimDAO.findUniqByObject("name", name);
		return moim;
	}
	@Transactional(readOnly = true)
	public Moim_Member getMemberFromUserId(long moimid, long id) {
		Moim_Moim moim = moimDAO.findUniqByObject("id", moimid);
		List<Moim_Member> members = moim.getMembers();
		int size = members.size();
		for(int i = 0 ; i < size ; i ++) {
			if(members.get(i).getUserId() == id)
				return members.get(i);
		}
		return null;
	} 
	@Transactional
	public void addMoim(Moim_Moim moim){
		moimDAO.save(moim);
	}
	
	@Transactional
	public Moim_User addMoim(String userName,long moimId){
		Moim_Moim moim = moimDAO.select(moimId);
		Moim_User user = userDAO.findUniqByObject("name", userName);
		user.addMoim(moim);
		moim.addUser(user);
		return user;
	}
	@Transactional
	public void deleteMoim(Moim_Moim moim){
		moimDAO.delete(moim);
	}
	@Transactional
	public void addMember(long moim_id, Moim_Member member){
		Moim_Moim moim = getMoim(moim_id);
		member.setMoim(moim);
		moim.addMember(member);
	}
	@Transactional
	public void deleteMember(long moim_id, Moim_Member member){
		Moim_Moim moim = getMoim(moim_id);
		moim.deleteMember(member);
	}
	
	@Transactional(readOnly = true)
	public boolean titleExists(String title) {
		return moimDAO.rowExists("title", title);
	}
}
